package com.tandashi.springbootstudy01.service.impl;

import com.tandashi.springbootstudy01.dao.test.SourceDataDao;
import com.tandashi.springbootstudy01.entity.test.SourceData;
import com.tandashi.springbootstudy01.service.SourceDataService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * (SourceDataTmp)表服务实现类
 *
 * @author makejava
 * @since 2023-04-08 21:49:03
 */
@Service
public class SourceDataServiceImpl implements SourceDataService {
    @Resource
    private SourceDataDao sourceDataDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public SourceData queryById(Long id) {
        return this.sourceDataDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param sourceData 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<SourceData> queryByPage(SourceData sourceData, PageRequest pageRequest) {
        long total = this.sourceDataDao.count(sourceData);
        return new PageImpl<>(this.sourceDataDao.queryAllByLimit(sourceData, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param sourceData 实例对象
     * @return 实例对象
     */
    @Override
    public SourceData insert(SourceData sourceData) {
        this.sourceDataDao.insert(sourceData);
        return sourceData;
    }

    /**
     * 修改数据
     *
     * @param sourceData 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional
    public SourceData update(SourceData sourceData) {
        this.sourceDataDao.update(sourceData);
        //int i = 1/0;
        return this.queryById(sourceData.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.sourceDataDao.deleteById(id) > 0;
    }

    @Transactional
    public SourceData testB(Long id){
        SourceData tmp = this.queryById(id);
        tmp.setName("测试事务B");
        SourceData update = this.update(tmp);

        return update;
    }
}
